package cn.jinjimi.app.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import bolts.Task;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.util.HttpProtocolHelper;
import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.domain.data.net.API;
import cn.jinjimi.domain.data.net.FileService;
import cn.jinjimi.domain.entity.UploadedFile;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 *
 * @author zhenhua
 * @date 2018/2/6
 */

public class FileController {

    public static Task<List<UploadedFile>> uploadFile(final Map<String, File> map) {
        return Task.callInBackground(new Callable<List<UploadedFile>>() {
            @Override
            public List<UploadedFile> call() throws Exception {
                List<UploadedFile> uploaded = new ArrayList<>();
                if (AccountManager.getInstance().isLogin()) {
                    String token = AccountManager.getInstance().getToken();
                    Response<ResponseBody> res = API.create(FileService.class)
                                                    .uploadFile(token, HttpProtocolHelper.convert2Parts(map))
                                                    .execute();

                    if (res != null && res.isSuccessful()) {
                        Type type = new TypeToken<List<UploadedFile>>(){}.getType();
                        List<UploadedFile> result = GsonUtils.fromJson(res.body().string(), type);
                        if (result != null) {
                            uploaded.addAll(result);
                        }
                    }
                }
                return uploaded;
            }
        });
    }
}
